from django.db.models import Avg, Count, Sum
from django.db.models.expressions import Ref
from django.db.models.query import QuerySet
from books.models import *


def run():
    # qs = Books.objects.all().values('author').annotate(avg_price=Avg('price'), book_count=Count('id')).order_by('book_count')
    # qs = Books.objects.all().annotate(book_count=Count('id'))
    # print(qs)
    # qs = Books.objects.all().values('author').annotate(book_count=Count('id'))
    # print(qs)
    # qs = Books.objects.all().annotate(book_count=Count('id')).values('author')
    # print(qs)
    # qs = Books.objects.all().aggregate(Sum('price'), avg_price=Avg('price'))
    qs = Books.objects.all()
    kwargs = {'avg_price': Avg('price'), 'price_sum': Sum('price')}
    query = qs.query
    for (alias, aggregate_expr) in kwargs.items():
        query.add_annotation(aggregate_expr, alias, is_summary=True)
        annotation = query.annotations[alias]
        if not annotation.contains_aggregate:
            raise TypeError("%s is not an aggregate expression" % alias)
        for expr in annotation.get_source_expressions():
            if expr.contains_aggregate and isinstance(expr, Ref) and expr.refs in kwargs:
                name = expr.refs
                print(
                    "Cannot compute %s('%s'): '%s' is an aggregate"
                    % (annotation.name, name, name)
                )
    res = query.get_aggregation('default', kwargs)
    print(res)
    # print(qs)
    # for q in qs:
    #     print(q)
